<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '新增项目' : '编辑项目'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" top="20px" :width="900">
    <a-scrollbar style="height: calc(100vh - 200px); overflow: auto">
      <div>
        <div class="title-bar">基础信息</div>
        <div>
          <div class="item mt10">
            <a-space>
              <div class="item-title">服务内容：</div>
              <div class="item-val">
                <a-input v-model="form.serContent" show-word-limit max-length="40" allow-clear placeholder="请用一句话描述你们提供的服务" />
              </div>
            </a-space>
          </div>
          <div class="item mt10" v-if="props.taskType == 'NEW_PRODUCT_PICTURE'">
            <a-space>
              <div class="item-title">原图来源：</div>
              <div class="item-val">
                <a-radio-group v-model="form.originPicSource" @change="radioChange">
                  <a-radio value="REAL_SHOOT">实物拍摄</a-radio>
                  <a-radio value="C4D_RENDER">CAD渲染</a-radio>
                  <a-radio value="APARTY_PROVIDE">甲方提供</a-radio>
                </a-radio-group>
              </div>
            </a-space>
          </div>
          <div class="item mt10" v-if="props.taskType == 'SHOOT_VIDEO'">
            <a-space>
              <div class="item-title">拍摄方式：</div>
              <div class="item-val">
                <a-radio-group v-model="form.shootType" @change="radioChangeShootVideo">
                  <a-radio value="REAL_SHOOT">实物拍摄</a-radio>
                  <a-radio value="RENDER_SHOOT">渲染拍摄</a-radio>
                </a-radio-group>
              </div>
            </a-space>
          </div>
          <div class="item mt10">
            <a-space>
              <div class="item-title">执行周期：</div>
              <div class="item-val" style="width: 200px">
                <a-input-number v-model="form.executeCycle" hide-button allow-clear />
              </div>
              <div>天</div>
              <div class="common-text">甲方承诺的执行周期，就是这个任务开始执行到交付的时间，不包含排期的时间</div>
            </a-space>
          </div>
          <div class="item mt10">
            <a-space>
              <div class="item-title">报价：</div>
              <div class="item-val" style="width: 200px">
                <a-input-number v-model="form.amtQuote" hide-button allow-clear />
              </div>
              <div>元/单</div>
            </a-space>
          </div>
        </div>
        <div class="title-bar">设置交付内容</div>
        <a-table size="mini" v-model:selected-keys="types" row-key="nodeType" class="table-singe-line" :data="deliveryData" :row-selection="['NEW_PRODUCT_PICTURE', 'SHOOT_VIDEO'].includes(props.taskType) ? rowSelection : undefined" :pagination="false">
          <template #columns>
            <a-table-column title="作业节点" :width="80" #cell="{ record }">
              {{ nodeMap[record.nodeType] }}
            </a-table-column>
            <a-table-column title="交付内容" :width="180" #cell="{ record }">
              <div style="margin-bottom: 5px" v-for="(item, index) in record.taskContentList" :key="index">
                <a-space>
                  <div style="width: 50px; text-align: right">{{ deliveryMap[item.contentType] }}：</div>
                  <div style="width: 200px">
                    <a-input-number v-model="item.quantity" hide-button allow-clear placeholder="请输入" />
                  </div>
                  <div>张</div>
                </a-space>
              </div>
            </a-table-column>
            <a-table-column :width="200">
              <template #title>
                <a-popover content="业绩分摊，是指该项目的每个交付节点定义价格，便于任务乙方统计任务执行人的业绩收入，分摊合计金额<=报价金额">
                  <p>
                    <span>分摊业绩金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <a-space>
                  <div style="width: 200px">
                    <a-input-number v-model="record.amount" hide-button allow-clear placeholder="请输入" />
                  </div>
                  <div>元</div>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>

        <div class="title-bar">服务描述</div>
        <div style="width: 100%; height: 300px">
          <editor v-model="form.serDesc" />
        </div>
      </div>
    </a-scrollbar>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { TableRowSelection, Message } from '@arco-design/web-vue'
  import { nodeMap, deliveryMap } from './map'
  import { saveTaskService, updateTaskService } from '@/api/task'
  import editor from '@/components/wangeditor/editor.vue'
  import _, { includes } from 'lodash-es'
  import { remove } from 'jszip'
  const rowSelection = ref<TableRowSelection>({
    type: 'checkbox',
    width: 40,
    // showCheckedAll: true,
    onlyCurrent: false,
  })
  let props = defineProps(['modelValue', 'type', 'info', 'taskType', 'configId'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let submitLoading = ref(false)
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let form = ref({
    serContent: '',
    originPicSource: 'REAL_SHOOT',
    shootType: 'REAL_SHOOT',
    executeCycle: '',
    amtQuote: '',
    enabled: true,
    serDesc: '',
    taskNodeList: [],
  })
  let types: any = ref([])

  const deliveryData: any = ref([])
  const NEW_PRODUCT_PICTURE_deliveryData = ref([
    { nodeType: 'RENDER', disabled: true, taskContentList: [{ contentType: 'ORIGINAL_PICTURE', quantity: 1 }], amount: 0 },
    { nodeType: 'SHOOT_VIDEO', disabled: true, taskContentList: [{ contentType: 'ORIGINAL_PICTURE', quantity: 1 }], amount: 0 },
    { nodeType: 'FIX_MAIN_PICTURE', disabled: true, taskContentList: [{ contentType: 'MAIN_PICTURE', quantity: 1 }], amount: 0 },
    { nodeType: 'FIX_SCENE_PICTURE', disabled: true, taskContentList: [{ contentType: 'SCENE_PICTURE', quantity: 1 }], amount: 0 },
    {
      nodeType: 'FILL_PICTURE',
      taskContentList: [
        { contentType: 'POSTER_PICTURE', quantity: 1 },
        { contentType: 'SIZE_PICTURE', quantity: 1 },
        { contentType: 'MOUTH_PICTURE', quantity: 1 },
      ],
      amount: 0,
    },
  ])
  const FIX_PICTURE_deliveryData = ref([{ nodeType: 'FIX_PICTURE', disabled: true, taskContentList: [{ contentType: 'FIX_PICTURE', quantity: 1 }], amount: 0 }])
  const SHOOT_VIDEO_deliveryData = ref([
    { nodeType: 'RENDER', disabled: true, taskContentList: [{ contentType: 'VIDEO', quantity: 1 }], amount: 0 },
    { nodeType: 'SHOOT_VIDEO', disabled: true, taskContentList: [{ contentType: 'VIDEO', quantity: 1 }], amount: 0 },
    { nodeType: 'CLIP_VIDEO', disabled: true, taskContentList: [{ contentType: 'VIDEO', quantity: 1 }], amount: 0 },
  ])
  const POSTER_SHOP_DESIGN_deliveryData = ref([{ nodeType: 'DESIGN_POSTER', disabled: true, taskContentList: [{ contentType: 'POSTER_PICTURE', quantity: 1 }], amount: 0 }])

  const CHANGE_DIAMOND_COLOR_deliveryData = ref([{ nodeType: 'CHANGE_DIAMOND_COLOR', disabled: true, taskContentList: [{ contentType: 'WINDOW_PICTURE', quantity: 1 }], amount: 0 }])
  const HAND_DRAWN_DESIGN_deliveryData = ref([{ nodeType: 'HAND_DRAWN_DESIGN', disabled: true, taskContentList: [{ contentType: 'DRAW_PICTURE', quantity: 1 }], amount: 0 }])

  const initTableData = () => {
    switch (props.taskType) {
      case 'NEW_PRODUCT_PICTURE':
        // 初始化的时候没有渲染的选项，所以先去掉
        let arr = _.cloneDeep(NEW_PRODUCT_PICTURE_deliveryData.value)
        deliveryData.value = arr.slice(1)
        // 直接选中
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
      case 'FIX_PICTURE':
        deliveryData.value = FIX_PICTURE_deliveryData.value
        // 直接选中
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
      case 'SHOOT_VIDEO':
        let arr1 = _.cloneDeep(SHOOT_VIDEO_deliveryData.value)
        deliveryData.value = arr1.slice(1)
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
      case 'POSTER_SHOP_DESIGN':
        deliveryData.value = POSTER_SHOP_DESIGN_deliveryData.value
        // 直接选中
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
      case 'HAND_DRAWN_DESIGN':
        deliveryData.value = HAND_DRAWN_DESIGN_deliveryData.value
        // 直接选中
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
      case 'CHANGE_DIAMOND_COLOR':
        deliveryData.value = CHANGE_DIAMOND_COLOR_deliveryData.value
        // 直接选中
        types.value = []
        deliveryData.value.forEach((e: any) => {
          if (e.disabled) types.value.push(e.nodeType)
        })
        break
    }
  }

  const radioChange = (val: string) => {
    // 因为不同类型只有 渲染和拍摄不一样，所以直接切数组来组装成选项
    let arr = _.cloneDeep(NEW_PRODUCT_PICTURE_deliveryData.value)
    if (val == 'REAL_SHOOT') {
      deliveryData.value = arr.slice(1)
    } else if (val == 'C4D_RENDER') {
      let newArr = arr[0]
      deliveryData.value = [newArr, ...arr.slice(2)]
    } else {
      deliveryData.value = arr.slice(2)
    }
    // if (props.type == 'edit' && val == props.info.originPicSource) deliveryData.value = props.info.taskNodeList
    types.value = []
    deliveryData.value.forEach((e: any) => {
      if (e.disabled) types.value.push(e.nodeType)
    })
  }

  const radioChangeShootVideo = (val: string) => {
    let arr = _.cloneDeep(SHOOT_VIDEO_deliveryData.value)
    if (val == 'REAL_SHOOT') {
      deliveryData.value = arr.slice(1)
    } else {
      let newArr = arr[0]
      deliveryData.value = [newArr, ...arr.slice(2)]
    }
    // if (props.type == 'edit' && val == props.info.shootType) deliveryData.value = props.info.taskNodeList
    types.value = []
    deliveryData.value.forEach((e: any) => {
      if (e.disabled) types.value.push(e.nodeType)
    })
  }

  const submit = async () => {
    let arr: any = []
    let valid = { nodeType: '', flag: false }

    deliveryData.value.forEach((e: any) => {
      let index = types.value.findIndex((el: any) => e.nodeType == el)
      if (index != -1) arr.push(e)
    })

    if (props.taskType == 'SHOOT_VIDEO' && form.value.shootType == 'RENDER_SHOOT') {
      form.value.originPicSource = ''
    }

    if (['FIX_PICTURE', 'POSTER_SHOP_DESIGN', 'CHANGE_DIAMOND_COLOR', 'HAND_DRAWN_DESIGN'].includes(props.taskType)) {
      form.value.originPicSource = ''
      form.value.shootType = ''
    }
    form.value.taskNodeList.forEach((e: any) => {
      let num = 0
      e.taskContentList.forEach((el: any) => {
        num += el.quantity
      })
      if (num == 0) {
        valid.nodeType = e.nodeType
        valid.flag = true
      }
    })

    if (valid.flag) {
      return Message.error(`作业节点（${nodeMap[valid.nodeType]}）中交付内容数必须大于一张`)
    }
    form.value.taskNodeList = arr
    let params: any = {
      configId: props.configId,
      taskService: form.value,
    }

    try {
      submitLoading.value = true
      let res = null
      if (props.type == 'add') {
        res = await saveTaskService(params)
      } else {
        res = await updateTaskService(params)
      }
      if (res) {
        Message.success('保存成功')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const showEditInfo = () => {
    if (props.type == 'edit') {
      form.value = _.cloneDeep(props.info)
      // 选项重新定义
      if (props.taskType == 'NEW_PRODUCT_PICTURE') {
        radioChange(props.info.originPicSource)
        // 反选的数据勾选上
        types.value = []
        form.value.taskNodeList.forEach((e: any) => {
          types.value.push(e.nodeType)
        })
      } else if (props.taskType == 'SHOOT_VIDEO') {
        radioChangeShootVideo(props.info.shootType)
        // 反选的数据勾选上
        types.value = []
        form.value.taskNodeList.forEach((e: any) => {
          types.value.push(e.nodeType)
        })
      } else {
        initTableData()
      }

      // 将用户的数据回填
      deliveryData.value.forEach((e: any) => {
        let index = form.value.taskNodeList.findIndex((el: any) => e.nodeType == el.nodeType)
        if (index != -1) {
          let item: any = _.cloneDeep(form.value.taskNodeList[index])
          e.taskContentList = item.taskContentList
          e.amount = item.amount
        }
      })
    }
  }

  onMounted(() => {
    if (props.type == 'add') {
      initTableData()
    } else {
      showEditInfo()
    }
  })
</script>

<style lang="less" scoped>
  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .item {
    width: 100%;
    .item-title {
      width: 70px;
      text-align: right;
    }
    .item-val {
      width: 400px;
    }
  }
</style>
